# api/models.py
import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings

class UserProfile(models.Model):
    ROLE_STUDENT = 'student'
    ROLE_TEACHER = 'teacher'
    ROLE_ADMIN = 'admin'
    ROLE_CHOICES = [
        (ROLE_STUDENT, 'Student'),
        (ROLE_TEACHER, 'Teacher'),
        (ROLE_ADMIN, 'SuperAdmin'), # 'SuperAdmin' vs 'admin' - be consistent
    ]

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role = models.CharField(
        max_length=20,
        choices=ROLE_CHOICES,
        default=ROLE_STUDENT # 设置一个默认角色
    )

    def __str__(self):
        return f"{self.user.username} - {self.get_role_display()}" # Use get_FOO_display for choices
    
    @property
    def is_teacher(self):
        return self.role == self.ROLE_TEACHER
    
    @property
    def is_admin(self):
        return self.role == self.ROLE_ADMIN
    
    @property
    def is_student(self):
        return self.role == self.ROLE_STUDENT

# 学生信息表（与 User 关联）
class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student')
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    gender = models.CharField(max_length=10)
    email = models.EmailField()
    group_id = models.IntegerField(default=0)

    class Meta:
        db_table = 'student'

    def __str__(self):
        return self.name
    
@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    # instance.userprofile.save() # 如果UserProfile有其他字段需要从User同步，可以在这里操作

# api/models.py 添加
class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=108)
    email = models.EmailField()
    department = models.CharField(max_length=100)
    managed_groups = models.ManyToManyField('StudentGroup', blank=True, related_name='managing_teachers')
    
    def __str__(self):
        return self.name

class StudentGroup(models.Model):
    name = models.CharField(max_length=100)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='teaching_groups')
    students = models.ManyToManyField(User, limit_choices_to={'userprofile__role': UserProfile.ROLE_STUDENT})
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return f"{self.name} (由 {self.teacher.name} 管理)"

# 阅读材料
class ReadingMaterial(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

# 单选题
class SingleChoiceQuestion(models.Model):
    text = models.TextField()
    option_a = models.CharField(max_length=255)
    option_b = models.CharField(max_length=255)
    option_c = models.CharField(max_length=255)
    option_d = models.CharField(max_length=255)
    correct_answer = models.CharField(max_length=1, choices=[
        ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D')
    ])

    def __str__(self):
        return self.text

# 多选题
class MultipleChoiceQuestion(models.Model):
    text = models.TextField()
    option_a = models.CharField(max_length=255)
    option_b = models.CharField(max_length=255)
    option_c = models.CharField(max_length=255)
    option_d = models.CharField(max_length=255)
    correct_answers = models.CharField(max_length=4)  # 存储格式：'AB', 'BCD' 等

    def __str__(self):
        return self.text

# 填空题
class FillInBlankQuestion(models.Model):
    text = models.TextField()
    correct_answer = models.CharField(max_length=255)
    fuzzy_answers = models.TextField(blank=True, null=True)  # 用逗号分隔的模糊答案

    def __str__(self):
        return self.text

# 任务
class Task(models.Model):
    name = models.CharField(max_length=255)
    reading_materials = models.ManyToManyField(ReadingMaterial, blank=True)
    single_choice_questions = models.ManyToManyField(SingleChoiceQuestion, blank=True)
    multiple_choice_questions = models.ManyToManyField(MultipleChoiceQuestion, blank=True)
    fill_in_blank_questions = models.ManyToManyField(FillInBlankQuestion, blank=True)

    def __str__(self):
        return self.name

# 实验
# api/models.py 修改Experiment模型
class Experiment(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    category = models.CharField(max_length=50, blank=True)  # 新增：分类
    difficulty = models.IntegerField(default=3)             # 新增：难度，1-5
    tasks = models.ManyToManyField(Task)
    created_by = models.ForeignKey(
        User, on_delete=models.CASCADE, 
        limit_choices_to={'userprofile__role__in': [UserProfile.ROLE_TEACHER, UserProfile.ROLE_ADMIN]},
        null=True, blank=True
    )
    assigned_groups = models.ManyToManyField(StudentGroup, blank=True)
    start_time = models.DateTimeField(default=datetime.datetime.now)
    end_time = models.DateTimeField(default=datetime.datetime.now)
    is_published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    allow_late_submission = models.BooleanField(default=False)
    max_submissions = models.IntegerField(default=3)
    is_visible = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['-created_at']
# 学生实验进度
class StudentExperimentProgress(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)
    experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE)
    completed_tasks = models.ManyToManyField(Task, related_name='completed_by_students', blank=True)
    is_completed = models.BooleanField(default=False)
    submitted_at = models.DateTimeField(null=True, blank=True)
    score = models.FloatField(default=0)       
    max_score = models.FloatField(default=0)    


    def __str__(self):
        return f"{self.student.username} - {self.experiment.name}"

# 学生答题记录
class StudentAnswerRecord(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)
    experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE)
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    single_choice_answers = models.JSONField(default=dict)  # 格式: {"question_id": "answer"}
    multiple_choice_answers = models.JSONField(default=dict)  # 格式: {"question_id": ["A", "B"]}
    fill_in_blank_answers = models.JSONField(default=dict)  # 格式: {"question_id": "answer"}
    completed_at = models.DateTimeField(null=True, blank=True)
    def __str__(self):
        return f"{self.student.username} - {self.experiment.name}"

# api/models.py 添加
class ExperimentReport(models.Model):
    experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE)
    student = models.ForeignKey(User, on_delete=models.CASCADE,related_name='experiment_reports_as_student')
    total_score = models.FloatField()
    task_scores = models.JSONField()  # 格式: {"task_id": score}
    submitted_at = models.DateTimeField(auto_now_add=True)
    corrected_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                   limit_choices_to={'userprofile__role__in': [UserProfile.ROLE_TEACHER, UserProfile.ROLE_ADMIN]},related_name='corrected_reports')
    feedback = models.TextField(blank=True)
    
    def __str__(self):
        return f"{self.student.username} - {self.experiment.name} - {self.total_score}"

# 新增教师评分模型
class TeacherEvaluation(models.Model):
    experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE)
    student = models.ForeignKey(User, on_delete=models.CASCADE,related_name='received_evaluations')
    teacher = models.ForeignKey(User, on_delete=models.CASCADE, 
                              limit_choices_to={'userprofile__role': UserProfile.ROLE_TEACHER}, related_name='given_evaluations')
    score = models.FloatField()
    feedback = models.TextField()
    evaluated_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        unique_together = ('experiment', 'student', 'teacher')

# 新增实验公告模型
class ExperimentAnnouncement(models.Model):
    experiment = models.ForeignKey(Experiment, on_delete=models.SET_NULL,null=True,  # 允许数据库字段为空
        blank=True)
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_by = models.ForeignKey(User, on_delete=models.CASCADE,
                                 limit_choices_to={'userprofile__role__in': [UserProfile.ROLE_TEACHER, UserProfile.ROLE_ADMIN]})
    created_at = models.DateTimeField(auto_now_add=True)
    is_pinned = models.BooleanField(default=False)
    
    class Meta:
        ordering = ['-is_pinned', '-created_at']

# 新增代码评测功能
class CodeQuestion(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    input_format = models.TextField()
    output_format = models.TextField()
    sample_input = models.TextField()
    sample_output = models.TextField()
    time_limit = models.IntegerField(default=2)  # 单位：秒
    memory_limit = models.IntegerField(default=256)  # 单位：MB

    def __str__(self):
        return self.title
# 新增代码提交记录模型
class CodeSubmission(models.Model):
    question = models.ForeignKey(CodeQuestion, on_delete=models.CASCADE)
    student = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    code = models.TextField()
    submitted_at = models.DateTimeField(auto_now_add=True)
    is_graded = models.BooleanField(default=False)
    result = models.CharField(max_length=50, blank=True)
    score = models.FloatField(default=0)
    feedback = models.TextField(blank=True)
    def __str__(self):
        return f"{self.student.username} - {self.question.title}"